package com.office.reader;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import com.office.AbstractReader;

/**
 * 读取TXT文件
 * @author h
 *
 */
public class TextReader extends AbstractReader{

	/**
	 * 判断TXT文件的编码格式
	 * 
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	private static String getCharset(String fileName) throws IOException {

		@SuppressWarnings("resource")
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				fileName));
		int p = (bis.read() << 8) + bis.read();

		String code = null;

		switch (p) {
		case 0xefbb:
			code = "UTF-8";
			break;
		case 0xfffe:
			code = "Unicode";
			break;
		case 0xfeff:
			code = "UTF-16BE";
			break;
		default:
			code = "GBK";
		}
		return code;
	}

	/**
	 * 获取TXT文件的内容
	 * 
	 * @param filePath
	 * @return
	 */
	public static void readText(String filePath) {
		try {
			InputStreamReader isr = new InputStreamReader(new FileInputStream(
					filePath), getCharset(filePath));
			BufferedReader br = new BufferedReader(isr);

			StringBuffer sb = new StringBuffer();
			String temp = null;
			while ((temp = br.readLine()) != null) {
				sb.append(temp);
			}
			br.close();
			System.out.println(sb.toString());
		} catch (FileNotFoundException e) {
			e.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
